import { createRouter, createWebHistory } from "vue-router";
import Layout from "@/components/CommonLayout.vue";
import Login from "@/views/LoginPage.vue";
import Dashboard from "@/views/DashboardPage.vue";
import UserList from "@/views/UserList.vue";
import UserProfile from "@/views/UserProfile.vue";
import PondList from "@/views/PondList.vue";
import DeviceList from "@/views/DeviceList.vue";
import VideoList from "@/views/VideoList.vue";
import AlertList from "@/views/AlertList.vue";
import {
  checkTokenExpirationStatus,
  refreshAndGetNewAccessToken,
} from "@/utils/auth";
import { ElMessage } from "element-plus";

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/",
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: Dashboard,
      },
      {
        path: "users",
        name: "UserList",
        component: UserList,
      },
      {
        path: "profile",
        name: "UserProfile",
        component: UserProfile,
      },
      {
        path: "ponds",
        name: "PondList",
        component: PondList,
      },
      {
        path: "devices",
        name: "DeviceList",
        component: DeviceList,
      },
      {
        path: "videos",
        name: "VideoList",
        component: VideoList,
      },
      {
        path: "alerts",
        name: "AlertList",
        component: AlertList,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 登录页直接放行
  if (to.name === "Login") {
    next();
    return;
  }

  const accessToken = localStorage.getItem("accessToken");
  const refreshToken = localStorage.getItem("refreshToken");

  // 没有任何Token，强制登录
  if (!accessToken || !refreshToken) {
    next({ name: "Login" });
    return;
  }

  // 检查Token是否已过期
  if (checkTokenExpirationStatus("access")) {
    try {
      // 尝试刷新Token
      await refreshAndGetNewAccessToken();
      next();
    } catch (error) {
      // 刷新失败，强制登录
      ElMessage.error("登录已过期，请重新登录");
      next({ name: "Login" });
    }
  } else {
    // Token有效，直接放行
    next();
  }
});

export default router;
